package com.neusmart.tongrentang.activity;

import android.graphics.Bitmap;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.neusmart.common.activity.SlidingBaseActivity;
import com.neusmart.common.util.ImageLoaderUtil;
import com.neusmart.common.util.L;
import com.neusmart.common.view.MyToast;
import com.neusmart.common.view.photoview.Info;
import com.neusmart.common.view.photoview.PhotoView;
import com.neusmart.tongrentang.F;
import com.neusmart.tongrentang.R;
import com.neusmart.tongrentang.fragment.LeftMenuFragment;
import com.neusmart.tongrentang.fragment.MainFragment;
import com.neusmart.tongrentang.model.Photo;
import com.neusmart.tongrentang.model.ReLocationEvent;
import com.neusmart.tongrentang.util.IBrowsePhotos;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.viewpagerindicator.CirclePageIndicator;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;

public class MainActivity extends SlidingBaseActivity implements ViewPager.OnPageChangeListener, BDLocationListener, IBrowsePhotos {

    AlphaAnimation in = new AlphaAnimation(0, 1);
    AlphaAnimation out = new AlphaAnimation(1, 0);
    private MainFragment mainFragment;
    private LeftMenuFragment leftMenuFragment;
    //
    private boolean isExit;
    //
    private ViewPager mPhotoPager;
    private View mParent, mBg;
    private ProgressBar mProgressBar;
    private CirclePageIndicator mIndicator;
    //
    private LocationClient mLocClient;
    private ArrayList<PhotoView> viewContainer = new ArrayList<>();
    private Info infoTo;
    private Map<Integer, Info> infoMap;
    private int currentPos;//需要初始化

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        init();
    }

    private void init() {
        initLocation();
        initView();
        setListener();
    }

    protected void initLocation() {
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(this);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(5000);
        option.setIsNeedAddress(true);
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    private void initView() {
        mainFragment = new MainFragment();
        setContent(mainFragment);
        //
        leftMenuFragment = new LeftMenuFragment();
        setMenu(leftMenuFragment);
        //
        mPhotoPager = (ViewPager) findViewById(R.id.pager);
        mPhotoPager.setPageMargin((int) (getResources().getDisplayMetrics().density * 15));
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
        mIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
        //时间同PhotoView
        in.setDuration(500);//
        out.setDuration(500);//
        mParent = findViewById(R.id.parent);
        mBg = findViewById(R.id.bg);
    }

    private void setListener() {
        mIndicator.setOnPageChangeListener(this);
    }

    @Override
    public void onBackPressed() {
        if (mParent.isShown()) {
            mBg.startAnimation(out);
            viewContainer.get(currentPos).animaTo(infoTo, new Runnable() {
                @Override
                public void run() {
                    mParent.setVisibility(View.GONE);
                }
            });
        } else if (mainFragment.isReplyLayoutShown()) {
            mainFragment.hideReplyLayout();
        } else if (mainFragment.isCurrentIsNotIndex()) {
            mainFragment.switch2Index();
        } else {
            exitBy2Click();
        }
    }

    private void exitBy2Click() {
        Timer tExit;
        if (isExit) {
            exit();
        } else {
            isExit = true;
            showExitToast(R.mipmap.toast_icn_exclamation_mark, R.string.press_again_to_exit);
            tExit = new Timer();
            tExit.schedule(new TimerTask() {

                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        }
    }

    private void showExitToast(int resId, int textId) {
        MyToast.showImgAndTextToast(this, resId, textId);
    }

    private void exit() {
        finish();
        System.exit(0);
    }

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        if (bdLocation == null)
            return;
        if (mLocClient != null)//定位成功后，直接销毁定位
            mLocClient.stop();
        onReceiveLoc(bdLocation);
    }

    protected void onReceiveLoc(BDLocation location) {
        F.latitude = location.getLatitude();//纬度
        F.longitude = location.getLongitude();//经度
        String province = location.getProvince();
        String city = location.getCity();
        if (!TextUtils.isEmpty(province))
            F.lbsProvince = province.replace("省", "");
        if (!TextUtils.isEmpty(city))
            F.lbsCity = city.replace("市", "");
        F.location = location.getAddrStr();
        L.d("Location", "纬度：" + location.getLatitude()
                + "\n经度：" + location.getLongitude()
                + "\n省份：" + location.getProvince()
                + "\n城市：" + location.getCity()
                + "\n位置：" + location.getAddrStr());
    }

    @Override
    public void browsePhotos(final List<Photo> photos, int index, Map<Integer, Info> infoMap) {
        this.infoMap = infoMap;
        infoTo = infoMap.get(index);
        currentPos = index;
        viewContainer.clear();
        for (Photo photo : photos) {
            final PhotoView view = new PhotoView(this);
            view.enable();
            ImageLoaderUtil.display(photo.getUrl(), view, new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String s, View view) {
                    mProgressBar.setVisibility(View.VISIBLE);
                }

                @Override
                public void onLoadingFailed(String s, View view, FailReason failReason) {
                    mProgressBar.setVisibility(View.INVISIBLE);
                }

                @Override
                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                    mProgressBar.setVisibility(View.INVISIBLE);
                }

                @Override
                public void onLoadingCancelled(String s, View view) {
                    mProgressBar.setVisibility(View.INVISIBLE);
                }
            });
            view.setScaleType(ImageView.ScaleType.FIT_CENTER);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mBg.startAnimation(out);
                    view.animaTo(infoTo, new Runnable() {
                        @Override
                        public void run() {
                            mParent.setVisibility(View.GONE);
                        }
                    });
                }
            });
            viewContainer.add(view);
        }
        viewContainer.get(index).animaFrom(infoTo);
        mPhotoPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return photos.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView(viewContainer.get(position));
                return viewContainer.get(position);
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView((View) object);
            }
        });
        mPhotoPager.setCurrentItem(index);
        mIndicator.setViewPager(mPhotoPager);
        mParent.setVisibility(View.VISIBLE);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        currentPos = position;
        infoTo = infoMap.get(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        if (mLocClient != null)
            mLocClient.stop();
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(ReLocationEvent event) {
        initLocation();
    }

}
